<!--
 * @Autor: lh
 * @Date: 2024-02-24 14:09:06
 * @LastEditors: lh
 * @LastEditTime: 2024-03-08 13:41:25
 * @Description:  考试考题组件
-->
<script lang="ts" setup>
import { ref, reactive, computed, onMounted, watch } from "vue"
import { examinationType } from "./index"
import { examQuestionsSelectOne, examQuestionsSelectInfo } from "@/api/examination"
import { useRoute } from "vue-router"
import { ElMessage, ElMessageBox } from "element-plus"
import { insertUserExamRecord } from "@/api/examination"
import router from "@/router"

let route = useRoute()
let isLoading = ref(true) // 加载中

let data = ref<{
  title: string //  考试标题
  standardScore: string | number // 及格分数
  isLook: boolean // 查看答案
  isEnd: boolean // 是否交卷
  fraction: number // 考试分数
  topicArr: examinationType[] // 考试题目
}>({
  title: "考试标题",
  standardScore: 0,
  isLook: false,
  isEnd: false,
  fraction: 0,
  topicArr: []
})

onMounted(() => {
  examQuestionsSelectInfo(route.query.examId).then((resinfo: any) => {
    if (resinfo.code == 200) {
      let resdatainfo = resinfo.data
      data.value.title = resdatainfo.examName
      data.value.standardScore = resdatainfo.standardScore
      examQuestionsSelectOne({
        examId: route.query.examId,
        page: 1,
        pageSize: 1000
      }).then((res: any) => {
        console.log("examQuestionsSelectOne,---", res)
        if (res.code == 200) {
          let records = res.data.records
          console.log("records", records)

          data.value.topicArr = records.map((it: any) => {
            it.team = []
            if (it.optionA) it.team.push(it.optionA)
            if (it.optionB) it.team.push(it.optionB)
            if (it.optionC) it.team.push(it.optionC)
            if (it.optionD) it.team.push(it.optionD)
            if (it.optionE) it.team.push(it.optionE)
            if (it.optionF) it.team.push(it.optionF)
            if (it.optionG) it.team.push(it.optionG)
            it.value = ""
            return it
          })
          setTimeout(() => {
            isLoading.value = false
          }, 2 * 1000)
        }
      })
    }
  })
})

// const props = withDefaults(
//   defineProps<{
//     titile: string //  考试标题
//     topicArr: examinationType[] // 考试题目
//   }>(),

// )

watch(
  () => data.value.topicArr,
  (newVal, oldVal) => {
    console.log(newVal, "---newVal--")
    let fenshu = 0
    for (let i = 0, len = newVal.length; i < len; i++) {
      let it = newVal[i]
      let abcStr = IndexFilAbc(it.value)
      if (abcStr == it.correctAnswer) {
        fenshu += Number(it.score)
        continue
      }
    }
    data.value.fraction = fenshu
    console.log("fenshu---", fenshu)
  },
  {
    deep: true
  }
)

let exIndex = ref(0) // 当前考题

let completeNum = computed(() => {
  // 已答题数量
  return data.value.topicArr.filter((it) => {
    return (Array.isArray(it.value) && it.value.length > 0) || (!Array.isArray(it.value) && it.value !== "")
  }).length
})

// 考题类型过滤方法
let subjectTypeFil = (e: number) => {
  let obj = ["单选题", "多选题", "判断题", "问答题"]
  return obj[e - 1]
}
// 数组索引过滤成 字母
const IndexFilAbc = (e: number | any[]) => {
  let abcArr = ["A", "B", "C", "D", "E", "F", "G", "H"]
  if (Array.isArray(e)) {
    let arrss = []
    for (let i = 0; i < e.length; i++) {
      arrss.push(abcArr[e[i]])
    }
    return arrss.join("")
  } else {
    return abcArr[e]
  }
}
// //
// const AbcFilIndex = (e:number)
// 设置当前考题索引
const setKaotiIndex = (i: number) => {
  exIndex.value = i
  data.value.isLook = false
}
/**
 * 设置 考题上一题或者下一题
 * @params {i} number 1 为上一题 2 为下一题
 */
const setUpperOrNext = (i: number) => {
  if (i == 1) {
    exIndex.value--
  } else {
    exIndex.value++
  }
  data.value.isLook = false
}

// 交卷
const submitFn = () => {
  if (route.query.isExamination != "1") {
    ElMessage({ message: "预览版无法提交", type: "error" })
    return
  }
  if (completeNum.value < data.value.topicArr.length) {
    ElMessage({ message: "还没答完~", type: "error" })
    return
  }
  ElMessageBox.confirm("确认是否提交试卷?")
    .then(() => {
      let params = {
        beTestId: route.query.id,
        examId: route.query.examId,
        examScore: data.value.fraction,
        state: data.value.fraction >= data.value.standardScore ? 1 : 2,
        userExamQuestionsRecordVoList: []
      }
      params.userExamQuestionsRecordVoList = data.value.topicArr.map((it: any) => {
        it.userAnswer = it.value
        return it
      })
      insertUserExamRecord(params)
        .then((res: any) => {
          if (res.code == 200) {
            data.value.isEnd = true
          }
        })
        .catch(() => {})
    })
    .catch(() => {
      // catch error
    })
}
// 返回
const backFn = () => {
  router.back()
}
</script>
<template>
  <div class="examination">
    <el-skeleton :rows="5" v-if="isLoading" />
    <template v-else>
      <div class="examination_til">{{ data.title }}</div>
      <div class="examination_body">
        <div class="examination_body_l">
          <div class="examination_body_l_til">答题卡</div>
          <div class="examination_body_l_list">
            <div
              class="examination_body_l_it"
              v-for="(it, i) in data.topicArr"
              :key="i"
              :class="{
                active: exIndex == i,
                no_value: data.topicArr[i].value === '' || data.topicArr[i].value.length == 0
              }"
              @click="setKaotiIndex(i)"
            >
              {{ i + 1 }}
            </div>
          </div>
          <div class="examination_body_l_foot">
            <div class="examination_body_l_foot_til">答题进度:{{ completeNum }}/{{ data.topicArr.length }}</div>
            <div class="examination_body_l_foot_bar">
              <div
                class="examination_body_l_foot_bar_it"
                :style="{ width: (completeNum / data.topicArr.length) * 100 + '%' }"
              ></div>
            </div>
            <div
              class="examination_body_l_foot_btns"
              :class="{ active: completeNum >= data.topicArr.length }"
              @click="submitFn"
            >
              交卷
            </div>
          </div>
        </div>
        <div class="examination_body_r">
          <template v-if="data.topicArr.length > 0 && !data.isEnd">
            <div class="examination_body_r_til">
              {{ exIndex + 1 }}.
              {{ data.topicArr[exIndex].titleTags }}

              <span class="tipsbox">{{ subjectTypeFil(data.topicArr[exIndex].questionsType) }}</span>
              <span class="fenshu">({{ data.topicArr[exIndex].score }}分)</span>
              <span class="look" @click="data.isLook = !data.isLook">看答案</span>
            </div>
            <div class="examination_body_r_con">
              <!-- 单选 -->
              <template v-if="data.topicArr[exIndex].questionsType == 1">
                <el-radio-group v-model="data.topicArr[exIndex].value" class="ml-4">
                  <el-radio :label="k" size="large" v-for="(its, k) in data.topicArr[exIndex].team" :key="k">
                    {{ IndexFilAbc(k) }}.
                    {{ its }}
                  </el-radio>
                </el-radio-group>
              </template>
              <!-- 多选 -->
              <template v-if="data.topicArr[exIndex].questionsType == 2">
                <el-checkbox-group v-model="data.topicArr[exIndex].value">
                  <el-checkbox v-for="(its, k) in data.topicArr[exIndex].team" :key="k" :label="k">
                    {{ IndexFilAbc(k) }}.
                    {{ its }}
                  </el-checkbox>
                </el-checkbox-group>
              </template>
              <!-- 判断选 -->
              <template v-if="data.topicArr[exIndex].questionsType == 3">
                <el-radio-group v-model="data.topicArr[exIndex].value" class="ml-4">
                  <el-radio :label="k" size="large" v-for="(its, k) in data.topicArr[exIndex].team" :key="k">
                    {{ its }}
                  </el-radio>
                </el-radio-group>
              </template>
              <!-- 问答 -->
              <template v-if="data.topicArr[exIndex].questionsType == 4">
                <el-input
                  v-model="data.topicArr[exIndex].value"
                  :rows="4"
                  type="textarea"
                  placeholder="简单描述你的回答"
                />
              </template>
            </div>
            <div class="examination_body_r_daan" v-if="data.isLook">
              正确答案:{{ data.topicArr[exIndex].correctAnswer }}
            </div>
            <div class="examination_body_r_foot">
              <div class="foot_upper foot_btn" @click="setUpperOrNext(1)" :class="{ hui: exIndex == 0 }">上一题</div>
              <div
                class="foot_next foot_btn"
                @click="setUpperOrNext(2)"
                :class="{ hui: exIndex >= data.topicArr.length - 1 }"
              >
                下一题
              </div>
            </div>
          </template>
          <template v-else-if="data.isEnd">
            <div class="" v-if="data.fraction >= data.standardScore">
              <el-result icon="success" title="考试完成,已合格" sub-title="恭喜您,已通过考试~">
                <template #extra>
                  <el-button type="primary" @click="backFn">确认</el-button>
                </template>
              </el-result>
            </div>
            <div class="" v-else>
              <el-result
                icon="error"
                :title="'考试完成,未合格,得分:' + data.fraction + '分'"
                :sub-title="'及格分:' + data.standardScore + ',还差一点就及格了,继续努力吧~'"
              >
                <template #extra>
                  <el-button type="primary" @click="backFn">确认</el-button>
                </template>
              </el-result>
            </div>
          </template>
        </div>
      </div>
    </template>
  </div>
</template>
<style scoped lang="scss">
.examination {
  width: 100%;
  height: 100%;
  :deep(.el-radio) {
    width: 100%;
    box-sizing: border-box;
    margin: 0;
  }
  :deep(.el-checkbox) {
    width: 100%;
    box-sizing: border-box;
    margin: 0;
  }
  &_til {
    text-align: center;
    font-size: 18px;
    color: #333;
    line-height: 40px;
    letter-spacing: 2px;
  }
  &_body {
    height: calc(100% - 40px - 20px);
    // background: #fff;
    display: flex;

    width: 100%;
    box-sizing: border-box;
    padding: 0 20px;
    &_l {
      width: 200px;
      height: 100%;
      overflow-y: auto;
      background: #fff;
      box-sizing: border-box;
      padding: 10px 6px;
      border-radius: 10px;
      margin-right: 10px;
      position: relative;
      &_til {
        font-size: 16px;
        text-align: center;
        line-height: 32px;
        position: relative;
        border-bottom: 1px #ccc solid;
        &::after {
          content: "";
          background: #409eff;
          width: 35%;
          position: absolute;
          height: 1.5px;
          left: 50%;
          bottom: 0;
          transform: translateX(-50%);
          z-index: 2;
        }
      }
      &_list {
        display: flex;
        justify-content: flex-start;
        flex-wrap: wrap;
      }
      &_it {
        width: 28px;
        height: 28px;
        line-height: 28px;
        text-align: center;
        border-radius: 2px;
        background: #ccc;
        margin: 10px 9px 0 0;
        font-size: 14px;
        cursor: pointer;
        &.active {
          background: #409eff;
          color: #fff;
        }
        &.no_value {
          position: relative;
          &::after {
            content: "";
            position: absolute;
            width: 4px;
            height: 4px;
            border-radius: 50%;
            background: red;
            right: -2px;
            top: -2px;
          }
        }
      }
      &_foot {
        box-sizing: border-box;
        padding: 20px;
        position: absolute;
        left: 0;
        bottom: 0;
        border-top: 1px #eaeaea solid;
        width: 100%;
        &_til {
          font-size: 14px;
          color: #666;
          letter-spacing: 1px;
        }
        &_bar {
          width: 100%;
          border-radius: 4px;
          height: 8px;
          border: 1px #eaeaea solid;
          overflow: hidden;
          margin-top: 10px;
          &_it {
            background: #409eff;
            height: 100%;
            max-width: 100%;
          }
        }
        &_btns {
          width: 80px;
          height: 28px;
          line-height: 28px;
          text-align: center;
          margin: 20px 0 0 auto;
          border-radius: 4px;
          color: #fff;
          background: #999;
          font-size: 14px;
          &.active {
            background: #409eff;
            cursor: pointer;
          }
        }
      }
    }
    &_r {
      flex: 1;
      height: 100%;
      overflow-y: auto;
      background: #fff;
      box-sizing: border-box;
      padding: 30px 10px;
      border-radius: 10px;
      position: relative;
      &_til {
        font-size: 16px;
        letter-spacing: 2px;
        line-height: 24px;
        .fenshu {
          color: red;
          margin: 0 6px;
          font-size: 14px;
        }
        .tipsbox {
          background: #dedede;
          color: #666;
          box-sizing: border-box;
          padding: 0 6px;
          line-height: 24px;
          font-size: 14px;
          border-radius: 2px;
        }
        .look {
          color: #409eff;
          border: 1px #409eff solid;
          box-sizing: border-box;
          height: 24px;
          line-height: 24px;
          border-radius: 2px;
          padding: 0 6px;
          font-size: 12px;
          display: inline-block;
          cursor: pointer;
        }
      }
      &_daan {
        background: #409eff;
        color: #fff;
        box-sizing: border-box;
        padding: 6px 4px;
        border-radius: 2px;
        font-size: 12px;
      }
      &_foot {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 60px;
        border-top: 1px #eaeaea solid;
        display: flex;
        box-sizing: border-box;
        align-items: center;
        justify-content: flex-end;
        .foot_btn {
          // background: #409eff;
          color: #409eff;
          height: 32px;
          width: 100px;
          text-align: center;
          margin-right: 20px;
          border: 1px #409eff solid;
          font-size: 16px;
          border-radius: 4px;
          line-height: 30px;
          cursor: pointer;
          box-sizing: border-box;
          user-select: none;
          &.hui {
            color: #999;
            border-color: #999;
          }
        }
      }
    }
  }
}
</style>
